package com.example.datastoredemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.createDataStore
import com.example.datastoredemo.protobuf.UserPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {

    private val dataStore: DataStore<UserPrefs.UserPreferences> =
        this.createDataStore(fileName = "UserPrefs.pb", serializer = UserPreferencesSerializer)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        GlobalScope.launch {
            dataStore.updateData {
                it.toBuilder().setResultPerPage(50).build()
                it.toBuilder().setAge(true).build()
            }

            dataStore.data.map {
                it
            }.collect { //flow 调用collect 开始消费数据
                Log.e("TAG", "onCreate1: ${it.toString()}")  //打印出 jackie
                Log.e("TAG", "onCreate2: ${it.pageNumber}")  //打印出 jackie
            }
        }

    }

    private suspend fun setValues(key: String, value: String) = withContext(Dispatchers.IO) {
        dataStore.updateData {
            it.toBuilder().setResultPerPage(50).build()
            it.toBuilder().setAge(true).build()
        }
    }
}